const config = require('./Configuration.js')
const getPolicyEncode = require('./getPolicy.js')
const getSignature = require('./GetSignature.js')
//日期规范工具函数
const dayjs = require('./dayjs')
const OBSupload = async function(filePath, that, func_ok, func_err) {
	if (!filePath) {
		wx.showToast({
			title: '文件路径不能为空',
			icon: '请重新选择路径'
		})
	} else {
		if(filePath.includes(config.EndPoint)){
			that.updateUserInfo(filePath)
			return;
		}
		const fileName = 'miniApp/avatar/' + dayjs(new Date().getTime()).format('YYYYMMDDHHmmss') +
			'.jpg' //指定上传到OBS桶中的对象名

		const OBSPolicy = {
			//设定policy内容
			expiration: '2025-12-31T12:00:00.000Z',
			conditions: [{
					bucket: config.bucket
				}, //Bucket name
				{
					key: fileName
				},
				// { 'content-type': 'image/png' },
				// { 'x-obs-acl': 'public-read' },

			]
		}

		const policyEncoded = getPolicyEncode(OBSPolicy) //计算policy编码值
		const signature = getSignature(policyEncoded, config.SecretKey) //计算signature

		uni.compressImage({
			src: filePath,
			// quality: 80, 	// 压缩质量
			success: (compressRes) => {
				const compressedFilePath = compressRes.tempFilePath;
				wx.uploadFile({
					url: config.EndPoint,
					filePath: compressedFilePath,
					name: 'file',
					header: {
						'content-type': 'multipart/form-data; boundary=-9431149156168'
					},
					formData: {
						AccessKeyID: config.AccessKeyId,
						policy: policyEncoded,
						signature: signature,
						key: fileName,
			
					},

					success: function(res) {
						console.log(res.statusCode) //打印响应状态码
						if (res.statusCode == '204') {
							const fileUrl = config.EndPoint + '/' + fileName
							// console.log('上传图片成功1111111', fileUrl)
							console.log('上传图片成功', res)
							//成功后要做的数据处理
							// that.updateUserInfo(res)
							if (func_ok) {
								func_ok(fileUrl)
							} else {
								that.updateUserInfo(fileUrl)
							}

							// that.triggerEvent('getImgList', [config.EndPoint + '/' + fileName])
						} else {
							console.log('上传图片失败', res)
						}
					},
					fail: function(e) {
						console.log(e)
						if (func_err) {
							func_err()
						} else {
							that.saveWithOutPic()
						}

					}
				})
			},
			fail: (err) => {
				console.log('图片压缩失败：', err);
			}
		});

	}
}

module.exports = OBSupload